import axios from "axios";
import { ElMessageBox, ElMessage, ElLoading } from "element-plus";

export const BASE_URL = import.meta.env.VITE_BASE_API;
// create an axios instance
const service = axios.create({
  baseURL: BASE_URL, // url = base url + request url
  // timeout: 10000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    const code = res.code || 200;
    const msg = res.msg || "--";
    if (code === 500) {
      if (Array.isArray(res.data)) {
        return res;
      }
      ElMessage.error(msg);
      return Promise.reject(new Error(msg));
    } else if (code !== 200) {
      ElMessage.error(msg);
      return Promise.reject("error");
    } else {
      return res;
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    ElMessage({
      message: error.msg || error,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
